package com.desire.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.desire.common.GiteeImgBedConstant;
import com.desire.common.Result;
import com.desire.common.ResultEnum;
import com.desire.common.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/giteeBlogImg")
@Transactional
@Api(tags = "博客Markdown上传图片操作接口")
public class GiteeBlogImgController {

    @PostMapping("/")
    @ApiOperation(value = "上传图片", notes = "上传图片")
//    @ApiImplicitParam(name = "imgFile", value = "图片", required = true, dataType = "file")
    public Result<Object> saveImg(@RequestParam(value = "imgFile", required = true) MultipartFile imgFile) throws Exception {
        Result<Object> result = ResultUtil.success(ResultEnum.SUCCESS, null);

        Map<String, Object> resultMap = new HashMap<>();

        String trueFileName = imgFile.getOriginalFilename();

        assert trueFileName != null;

        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));

        String fileName = System.currentTimeMillis() + "_" + IdUtil.randomUUID() + suffix;

        String paramImgFile = Base64.encode(imgFile.getBytes());

        //转存到gitee
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", GiteeImgBedConstant.ACCESS_TOKEN);
        paramMap.put("message", GiteeImgBedConstant.CREATE_REPOS_MESSAGE);
        paramMap.put("content", paramImgFile);

        String targetDir = GiteeImgBedConstant.IMG_FILE_DEST_PATH + fileName;
        String requestUrl = String.format(GiteeImgBedConstant.CREATE_REPOS_URL, GiteeImgBedConstant.OWNER,
                GiteeImgBedConstant.REPO_NAME, targetDir);

        System.out.println("requestUrl:" + requestUrl);

        String resultJson = HttpUtil.post(requestUrl, paramMap);

        JSONObject jsonObject = JSONUtil.parseObj(resultJson);
        System.out.println("jsonObject:" + jsonObject);
        if (jsonObject.getObj("commit") != null) {
            // 这个就是上传的图片的访问地址
            String resultImgUrl = GiteeImgBedConstant.GITPAGE_REQUEST_URL + targetDir;
            resultMap.put("resultImgUrl", resultImgUrl);
            resultMap.put("resultJson", resultJson);
            System.out.println(resultImgUrl);
            result.setCode(200);
            result.setMsg(resultImgUrl);
            result.setData(resultMap.toString());
        } else {
            result.setCode(401);
            result.setMsg(jsonObject.getStr("message"));
        }
        return result;
    }
}
